package com.smartcommunity.service.tag.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.smartcommunity.bean.constant.Constant;
import com.smartcommunity.bean.enumeration.ResultCode;
import com.smartcommunity.bean.enumeration.TagTargetEnum;
import com.smartcommunity.bean.model.Pager;
import com.smartcommunity.bean.model.Result;
import com.smartcommunity.dao.tag.TagDao;
import com.smartcommunity.entity.tag.ObjectTag;
import com.smartcommunity.entity.tag.Tag;
import com.smartcommunity.entity.tag.TagGroup;
import com.smartcommunity.entity.tag.TagTarget;
import com.smartcommunity.entity.tag.dto.AddTagDto;
import com.smartcommunity.entity.tag.dto.UpdateTagDto;
import com.smartcommunity.service.tag.TagService;
import com.smartcommunity.utils.ArrayUtils;
import com.smartcommunity.utils.StringUtils;
import com.smartcommunity.utils.ToolDateTime;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: BMSZHD2
 * Date: 2019-06-21
 * Time: 17:26
 */
@Slf4j
@Service
public class TagServiceImpl implements TagService{


    @Autowired
    TagDao tagDao;

    //扩展标签
    private static int TAG_EXT=1;

    //标签不共享
    private static int UNSHARE=0;

    //标签共享
    private static int SHARE=1;

    private static String APPLICATION="np-zhsq";

    @Override
    public Result addTag(AddTagDto bean) {
        Tag oldTag = tagDao.queryByName(bean.getName());
        if(oldTag!=null){
            return  Result.error(ResultCode.TAG_NAME_EXSIT);
        }
        Tag tag = new Tag();
        tag.setTagName(bean.getName());
        tag.setGroupId(bean.getGroupId());
        tag.setTagColor(bean.getTagColor());
        tag.setDeadline(bean.getDeadline());
        tag.setTagType(1);
        tag.setDeadTime(getDeadTime(bean.getDeadline()));
        tagDao.insertTag(tag);
        return Result.ok();
    }

    @Override
    public Result updateTag(UpdateTagDto bean) {
        Tag oldTag = tagDao.queryByName(bean.getName());
        if(oldTag!=null && oldTag.getId().intValue()!=bean.getTagId().intValue()){
            return  Result.error(ResultCode.TAG_NAME_EXSIT);
        }
        Tag tag = new Tag();
        tag.setId(bean.getTagId());
        tag.setGroupId(bean.getGroupId());
        tag.setTagName(bean.getName());
        tag.setTagColor(bean.getTagColor());
        tag.setDeadline(bean.getDeadline());
        tag.setDeadTime(getDeadTime(bean.getDeadline()));
        tagDao.updateTag(tag);
        return Result.ok();
    }

    private String getDeadTime(int deadline){
        String deadTime = null;
        String startTime = ToolDateTime.getFormatDate();
        switch (deadline){
            case Constant.TAG_VALID_FOREVER:
                deadTime = ToolDateTime.getAnyDate(startTime,500,0,0);
                break;
            case Constant.TAG_VALID_WEEK:
                deadTime = ToolDateTime.getAnyDate(startTime,0,0,7);
                break;
            case Constant.TAG_VALID_MONTH:
                deadTime = ToolDateTime.getAnyDate(startTime,0,1,0);
                break;
            case Constant.TAG_VALID_HALF_YEAR:
                deadTime = ToolDateTime.getAnyDate(startTime,0,6,0);
                break;
            case Constant.TAG_VALID_YEAR:
                deadTime = ToolDateTime.getAnyDate(startTime,1,0,0);
                break;
        }
        return deadTime;
    }

    @Override
    @Transactional
    public Result deleteTag(String tagIds) {

        if(StringUtils.isEmpty(tagIds)){
            return  Result.error(ResultCode.MIS_VALID_PARAM);
        }
        StringBuffer sb = new StringBuffer();
        for(Integer tagId : ArrayUtils.toIntList(tagIds)){
            int count = tagDao.queryCountByTagId(tagId);
            if(count != 0) {
                Tag tag = tagDao.getTagById(tagId);
                sb.append(tag.getTagName()).append(",");
                //标签有关联数据，禁止删除
                continue;
            }
        }
        //提示失败的标签名称
        if(sb.length()>0){
            String msg = sb.substring(0,sb.length()-1);
            return Result.error(ResultCode.TAG_HAVE_DATA.code(), String.format(ResultCode.TAG_HAVE_DATA.msg(), msg) );
        }
        //批量删除
        tagDao.deleteTags(tagIds);
        return  Result.ok();
    }

    /**
     * 根据对象证件号查询标签
     * @param queryParam
     * @return
     */
    @Override
    public List<Tag> getObjectTag(Map<String,Object> queryParam) {
        return tagDao.getObjectTag(queryParam);
    }

    @Override
    public void addObjectTag(String objId, String villageCode, List<Integer> tagList) {
        if(tagList==null || tagList.size()==0){
            return;
        }
        Map<String,Object> queryParam = new HashMap<>();
        queryParam.put("objectId",objId);
        queryParam.put("tagIds","");
        tagDao.deleteObjectTag(queryParam);
        List<ObjectTag> dataList = new ArrayList<ObjectTag>();
        for(Integer tagId : tagList){
            if(tagId!=null && tagId!=0){
                ObjectTag data = new ObjectTag(objId,villageCode,tagId);
                dataList.add(data);
            }
        }
        if(dataList.size()>0){
            tagDao.addObjectTag(dataList);
        }
    }

    private String addTagRequestBody(Integer tagTarget, Integer group, String name, int shareType, String tagId){
        JSONArray array = new JSONArray();
        JSONObject tagInfo = new JSONObject();
        tagInfo.put("shareFlag",shareType);
        tagInfo.put("sourceApplication",APPLICATION);
        tagInfo.put("status","1");
        tagInfo.put("tagId",tagId);
        tagInfo.put("tagIndexCode",group);
        tagInfo.put("tagName",name);
        tagInfo.put("tagType",tagTarget);
        array.add(tagInfo);
        JSONObject request = new JSONObject();
        request.put("dtos",array);
        return request.toJSONString();
    }

    @Override
    public Map<Integer,TagTarget> getTagTargetList() {
        List<TagGroup> tagGroupList = tagDao.getTagGroupList();
        if(tagGroupList!=null && tagGroupList.size()>0){
            Map<Integer, TagTarget> dataMap = new HashMap<Integer, TagTarget>();

            for(TagGroup tagGroup : tagGroupList){

                TagTarget tagTarget = dataMap.get(tagGroup.getTargetType());
                if(tagTarget==null){
                    tagTarget = new TagTarget();
                    tagTarget.setTargetType(tagGroup.getTargetType());
                    tagTarget.setTargetName(TagTargetEnum.getName(tagGroup.getTargetType()));
                    dataMap.put(tagGroup.getTargetType(),tagTarget);

                }
                List<TagGroup> groupList = tagTarget.getTagGroupList();
                if(groupList==null){
                    groupList = new ArrayList<TagGroup>();
                }
                groupList.add(tagGroup);
                tagTarget.setTagGroupList(groupList);
            }
            return dataMap;
        }
        return null;
    }

    @Override
    public Pager<Tag> getTagList(Map<String, Object> queryMap, int currentPage, int pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        List<Tag> entryList = tagDao.getTagList(queryMap);
        int total = (int) ((Page) entryList).getTotal();
        Pager<Tag> pageData  = new Pager<>(currentPage, pageSize, total);
        pageData.setList(entryList);
        return pageData;
    }
}
